import { useState } from 'react'
import styles from './index.module.scss'
import logo from '@/assets/logo.png'
import { Form, Input, Button, Checkbox, Card, message } from 'antd'
import { useDispatch } from 'react-redux'
import { login } from '@/store/actions/login.js'
import { useHistory } from 'react-router-dom'
export default function index () {
  const history = useHistory() // 拿到路由信息
  const [beLoggingIn, setBeLoggingIn] = useState(false)
  const dispatch = useDispatch()
  const onFinish = async (data) => {
    setBeLoggingIn(true)
    try {
      await dispatch(login(data))
      message.success('登录成功！~~~~')
      history.push('/layout')
    } catch (err) {
      message.error(err.response.data.message, 2)
      setBeLoggingIn(false)
    }
  }

  const onFinishFailed = () => {
    console.log('提交表单眼真失败')
  }

  return (
    <div className={styles.root}>
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        <Form
          validateTrigger={['onBlur', 'onChange']}
          name="basic"
          initialValues={{
            mobile: '13811111231',
            code: '246810',
            agreement: true
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off">
          <Form.Item
            name="mobile"
            rules={[
              { pattern: /^1\d{10}/, message: '请输入合法的手机号' },
              { required: true, message: '请输入手机号' }
            ]}>
            <Input placeholder="输入手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { pattern: /\d{6}/, message: '请输入6位验证码' },
              { required: true, message: '请输入验证码' }
            ]}>
            <Input />
          </Form.Item>

          <Form.Item name="agreement" valuePropName="checked">
            <Checkbox>
              我已阅读并同意<a>[用户协议]</a>和<a>[隐私条款]</a>
            </Checkbox>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              block
              loading={beLoggingIn}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
